package com.example.weight.householdWaste;

import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.Utility;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class CombustiblePutrescibleRecordActivity extends AppCompatActivity {

    String name, factory;

    private EditText et_comRead, et_putRead, et_reader, et_remark;

    private SharedPreferences preferences;

    private ItemAdapter adapter;
    private List<String> nameList;

    private PopupWindow popupWindow;

    private SimpleDateFormat sdf_time = new SimpleDateFormat();// 格式化时间
    private SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间

    private Date date = new Date();// 获取当前时间


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sdf_time.applyPattern("HH:mm");// a为am/pm的标记
        setContentView(R.layout.activity_combustible_putrescible_record);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.combustible_putrescible_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                CombustiblePutrescibleRecordActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

//        et_date = findViewById(R.id.combustible_putrescible_come_time);
        et_comRead = findViewById(R.id.combustion_read);
        et_putRead = findViewById(R.id.putrescible_read);
        et_reader =  findViewById(R.id.combustible_putrescible_reader);
        et_remark = findViewById(R.id.combustible_putrescible_remark);

        et_reader.setText(name);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/combustiblePerishable/getlast" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                carNum.setText(data.getString("wagonNumber"));
//                                comeTime.setText(data.getString("arrivalTime"));
//                                leaveTime.setText(data.getString("leaveTime"));}
////                                transportWeight.setText(data.getString("cleanWeight"));
////                                if (data.getString("cleanType").equals("可燃物"))
////                                    tranComb.setChecked(true);
////                                else
////                                    tranPutre.setChecked(true);
////                                restWeight.setText(data.getString("residueWeight"));
////                                if (data.getString("residueType").equals("可燃物"))
////                                    restComb.setChecked(true);
////                                else
////                                    restPutre.setChecked(true);
////                                comment.setText(data.getString("remarks"));
////                                Toast.makeText(CombustiblePutrescibleActivity.this,
////                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(CombustiblePutrescibleRecordActivity.this,
//                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

        // 设置输入记录缓存
        preferences = getSharedPreferences("combustible_putrescible", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("comment", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }

//        // 创建ListView
//        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
//        ListView listView = new ListView(this);
//        listView.setAdapter(adapter);
//        listView.setOnItemClickListener((parent, view, position, id) -> {
//            // 若有进行删除操作，更新nameList，否则nameList序号对不上
//            if (adapter.getDeletePos() >= 0) {
//                List<Item> tempItemList = adapter.getList();
//                nameList.clear();
//                for (Item item : tempItemList) {
//                    nameList.add(item.getName());
//                }
//            }
//            // 根据所选设置输入框文本
//            String result = nameList.get(position);
//            comment.setText(result);
//            popupWindow.dismiss();
//            hideInput();
//        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
//        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
//        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
//        int height = wManager.getDefaultDisplay().getHeight() / 8;
//        // 参数为 1.View 2.宽度 3.高度
//        popupWindow = new PopupWindow(listView ,width, WindowManager.LayoutParams.WRAP_CONTENT);
//        // 设置点击外部区域可以取消popupWindow
//        popupWindow.setOutsideTouchable(true);

//        comment.setOnFocusChangeListener((v, hasFocus) -> {
//            // 设置popupWindow显示,并且告诉它显示在那个View下面
//            if (hasFocus) {
//                // 若聚焦到该输入框，显示下拉列表
//                popupWindow.showAsDropDown(comment);
//            }
//        });

//        et_date.setOnFocusChangeListener((v, hasFocus) -> {
//            if (hasFocus) {
//                Calendar calendar = Calendar.getInstance();
//                int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
//                int MINUTE = calendar.get(Calendar.MINUTE);
//
//                TimePickerDialog timePickerDialog = new TimePickerDialog(CombustiblePutrescibleRecordActivity.this, 2,
//                        (view1, hourOfDay, minute) ->
//                                et_date.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
//                        ,HOUR
//                        ,MINUTE
//                        ,true);
//                timePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (which == DialogInterface.BUTTON_NEGATIVE) {
//                            //取消操作
//                            et_date.clearFocus();
//                        }
//                    }
//                });
//                timePickerDialog.show();
//            }
//        });
    }
//
//    public void selectComeTime(View view) {
//        Calendar calendar = Calendar.getInstance();
//        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
//        final int MINUTE = calendar.get(Calendar.MINUTE);
//
//        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
//                et_date.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
//                ,HOUR
//                ,MINUTE
//                ,true)
//                .show();
//    }

//    public void selectLeaveTime(View view) {
//        Calendar calendar = Calendar.getInstance();
//        final int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
//        final int MINUTE = calendar.get(Calendar.MINUTE);
//
//        new TimePickerDialog(this, 2, (view1, hourOfDay, minute) ->
//                leaveTime.setText(String.format("%02d",hourOfDay) +":"+ String.format("%02d",minute))
//                ,HOUR
//                ,MINUTE
//                ,true)
//                .show();
//    }
//
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        String weight = data.getStringExtra("weight");
//        if (isTransWeight)
//            transportWeight.setText(weight);
//        else
//            restWeight.setText(weight);
//    }
//
//    public void goWeightForTransport(View view) {
//        isTransWeight = true;
//        Intent intent = new Intent(CombustiblePutrescibleRecordActivity.this, WeightActivity.class);
//        startActivityForResult(intent, 1);
//    }
//
//    public void goWeightForRest(View view) {
//        isTransWeight = false;
//        Intent intent = new Intent(CombustiblePutrescibleRecordActivity.this, WeightActivity.class);
//        startActivityForResult(intent, 1);
//    }

    public void save(View view) {
//        if (et_date.getText().toString().equals("")) {
//            Toast.makeText(this, "请选择日期", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (et_comRead.getText().toString().equals("")) {
            Toast.makeText(this, "请填写可燃物表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (et_putRead.getText().toString().equals("")) {
            Toast.makeText(this, "请填写可腐物表读数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (et_reader.getText().toString().equals("")) {
            Toast.makeText(this, "请填写抄表人", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (et_remark.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写备注", Toast.LENGTH_SHORT).show();
//            return;
//        }
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
            .setPositiveButton("确定", (dialog, which) -> {
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新nameList
//                List<Item> tempItemList = adapter.getList();
//                if (tempItemList.size() != nameList.size()) {
//                    nameList.clear();
//                    for (Item item : tempItemList) {
//                        nameList.add(item.getName());
//                    }
//                }
                // 判断该输入框内容是否已存在，不存在则加入
//                String current = comment.getText().toString();
//                if (!current.equals("") && !nameList.contains(current)) {
//                    nameList.add(current);
//                }

                editor.putStringSet("comment", new HashSet<>(nameList));
                editor.apply();

                // 提交表单
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/combustiblePerishable/add";

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");

//                                    carNum.setText("");
//                                    comeTime.setText("");
//                                    leaveTime.setText("");
//                                    transportWeight.setText("");
//                                    restWeight.setText("");
//                                    comment.setText("");

                                    if (code.startsWith("2"))
                                        Toast.makeText(CombustiblePutrescibleRecordActivity.this,
                                                "保存成功", Toast.LENGTH_SHORT).show();
                                    else
                                        Toast.makeText(CombustiblePutrescibleRecordActivity.this,
                                                "保存失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(CombustiblePutrescibleRecordActivity.this,
                                "保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> map=new HashMap<>();
                        map.put("combustibleNumberstr", et_comRead.getText().toString());
                        map.put("combustibleTime", sdf_time.format(date));
                        map.put("perishableNumberstr", et_putRead.getText().toString());
                        map.put("perishableTime", sdf_time.format(date));
                        map.put("recordingPerson", name);
                        map.put("remarks", et_remark.getText().toString());
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();

    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
